<?php

namespace app\base\controller\miniapp\staff;

use app\base\logic\LogsLogic;

use app\base\model\CouponModel;

use app\base\model\logs\MemberBalanceLogsModel;

use app\base\model\logs\MemberCouponLogsModel;

use app\base\model\logs\MemberIntegralLogsModel;

use app\base\model\member\MemberBalanceModel;

use app\base\model\member\MemberCouponModel;

use app\base\model\member\MemberIntegralModel;

use app\base\model\member\MemberModel;

use app\base\model\order\BuyOrderModel;

use app\base\model\setting\SettingBalanceModel;

use app\base\model\setting\SettingIntegralModel;

use app\BaseController;

use app\common\logic\DataLogic;

use think\facade\Db;

use app\base\logic\MemberWalletLogic;



class Member extends BaseController{

    public function getMemberInfo()

    {

        $member_id=$this->request->param('member_id/d',0);

        if(null === $member = MemberModel::find($member_id)) return $this->error('会员不存在');

        if($member->is_delete != 0) return $this->error('会员不存在');

        if($member->shop_id != $this->request->shopId) return $this->error('会员不存在');

        $member->append(['hidden_mobile']);



        $balance = MemberBalanceModel::where([

                ['shop_id','=',$this->request->shopId],

                ['member_id','=',$member_id],

                ['valid_bg_time','<=',$this->request->time()]

            ])->sum('remain_balance') ?? 0;



        $integral = MemberIntegralModel::where([

                ['shop_id','=',$this->request->shopId],

                ['member_id','=',$member_id],

                ['expire_time','>',$this->request->time()]

            ])->sum('remain_integral') ?? 0;



        $coupon_count = MemberCouponModel::where([

                ['shop_id','=',$this->request->shopId],

                ['member_id','=',$member_id],

            ])->count() ?? 0;



        $detail=[

            'member_id'=>$member->member_id,

            'nick_name'=>$member->nick_name,

            'is_vip'=>$member->level ? 1 : 0,

            'level_name'=>$member->level ? $member->level->name : '普通会员',

            'hidden_mobile'=>$member->hidden_mobile,

            'face'=>$member->face,

            'level_discount'=>$member->level ? $member->level->discount : 10,

            'balance'=>$balance,

            'integral'=>$integral,

            'coupon_count'=>$coupon_count,

        ];

        $return=[

            'detail'=>$detail,

        ];

        return $this->success($return);



    }



    public function balanceRecharge()

    {

        //判断权限

        if (!in_array(2, $this->request->staff->add_value_jurisdiction)) {

            return $this->error('您没有余额充值的权限');

        }



        $member_id=$this->request->param('member_id/d',0);

        if(null === $member = MemberModel::find($member_id)) return $this->error('会员不存在');

        if($member->is_delete != 0)  return $this->error('会员不存在');

        if($member->shop_id != $this->request->shopId)   return $this->error('会员不存在');



        $balance= $this->request->param('balance/f',0);

        $give_balance =$this->request->param('give_balance/f',0);

        if($balance <=0 ) return $this->error('请填写充值金额，且金额不能小于等于0');



        Db::startTrans();

        try{

            $MemberWalletLogic = new MemberWalletLogic($this->request->shopId, $member_id);

            $res = $MemberWalletLogic->addBalance($balance, $give_balance, 2,'', $this->request->staffId);

            if($res == false){

                Db::rollback();

                return $this->error($MemberWalletLogic->getError());

            }

            Db::commit();

            return $this->success('操作成功');

        }catch(\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }

    }



    public function writeOffBalance()

    {

        //判断权限

        if ($this->request->staff->write_off_jurisdiction !=1) {

            return $this->error('您没有核销的权限');

        }



        $member_id=$this->request->param('member_id/d',0);

        if(null === $member = MemberModel::find($member_id)) return $this->error('会员不存在');

        if($member->is_delete != 0)  return $this->error('会员不存在');

        if($member->shop_id != $this->request->shopId)   return $this->error('会员不存在');



        $balance= $this->request->param('balance/f',0);

        $original_deduction =$this->request->param('original_deduction/f',0);

        if($balance <=0 ) return $this->error('请填写扣除金额，且金额不能小于等于0');

        if($original_deduction <= 0) return $this->error('请填写原本扣除金额，金额不能小于等于0');

        if($original_deduction < $balance) return $this->error('原本扣除的金额不能小于实际扣除的金额');



        $remarks=$this->request->param('remarks');



        Db::startTrans();

        try{

            $MemberWalletLogic = new MemberWalletLogic($this->request->shopId, $member_id);

            $res = $MemberWalletLogic->useBalance($balance, $original_deduction, 6,$remarks, $this->request->staffId);

            if($res == false){

                Db::rollback();

                return $this->error($MemberWalletLogic->getError());

            }

            Db::commit();

            return $this->success('操作成功');

        }catch(\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }



    }



    public function integralRecharge()

    {

        //判断权限

        if (!in_array(3, $this->request->staff->add_value_jurisdiction)) {

            return $this->error('您没有增加积分的权限');

        }



        $member_id=$this->request->param('member_id/d',0);

        if(null === $member = MemberModel::find($member_id)) return $this->error('会员不存在');

        if($member->is_delete != 0)  return $this->error('会员不存在');

        if($member->shop_id != $this->request->shopId)   return $this->error('会员不存在');



        $integral= $this->request->param('integral/d',0);

        if($integral <=0 ) return $this->error('请填写充值积分，且积分不能小于等于0');





        Db::startTrans();

        try{

            

            $MemberWalletLogic = new MemberWalletLogic($this->request->shopId, $member_id);

            $res = $MemberWalletLogic->addIntegal($integral, 1,'', $this->request->staffId);

            if($res == false){

                Db::rollback();

                return $this->error($MemberWalletLogic->getError());

            }

          

            Db::commit();

            return $this->success('操作成功');

        }catch(\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }

    }



    public function writeOffIntegral()

    {

        //判断权限

        if ($this->request->staff->write_off_jurisdiction !=1) {

            return $this->error('您没有核销的权限');

        }



        $member_id=$this->request->param('member_id/d',0);

        if(null === $member = MemberModel::find($member_id)) return $this->error('会员不存在');

        if($member->is_delete != 0)  return $this->error('会员不存在');

        if($member->shop_id != $this->request->shopId)   return $this->error('会员不存在');



        $integral= $this->request->param('integral/d',0);

        if($integral <=0 ) return $this->error('请填写充值积分，且积分不能小于等于0');



        $remarks=$this->request->param('remarks');



        Db::startTrans();

        try{

            $MemberWalletLogic = new MemberWalletLogic($this->request->shopId, $member_id);

            $res = $MemberWalletLogic->useIntegral($integral, 4,$remarks, $this->request->staffId);

            if($res == false){

                Db::rollback();

                return $this->error($MemberWalletLogic->getError());

            }

            Db::commit();

            return $this->success('操作成功');

        }catch(\Exception $e){

            Db::rollback();

            return $this->error($e->getMessage());

        }

    }



    public function chooseCoupon()

    {

        $today=date("Y-m-d",$this->request->time());

        $where=[

            ['shop_id','=',$this->request->shopId],

            ['is_delete','=',0],

            ['status','=',1],

            ['end_time','>=',$today]

        ];



        $datas=CouponModel::where($where)

            ->order(['update_time'=>'desc','add_time'=>'desc'])

            ->field('coupon_id,name,valid_bg_time,valid_end_time,coupon_money,money_limit')

            ->limit($this->request->limit)->page($this->request->page)

            ->select()->toArray();

        return $this->success(['datas'=>$datas]);

    }



    public function sendCoupon()

    {

        //判断权限

        if (!in_array(4, $this->request->staff->add_value_jurisdiction)) {

            return $this->error('您没有送券的权限');

        }



        $member_id=$this->request->param('member_id/d',0);

        if(null === $member = MemberModel::find($member_id)) return $this->error('会员不存在');

        if($member->is_delete != 0)  return $this->error('会员不存在');

        if($member->shop_id != $this->request->shopId)   return $this->error('会员不存在');



        $coupon_ids = $this->request->param('coupon_ids/a',[]);

        if(empty($coupon_ids)) return $this->error('请选择优惠券');

        $coupon_data=CouponModel::where([

            ['coupon_id','in',$coupon_ids],

            ['shop_id','=',$this->request->shopId],

            ['is_delete','=',0],

            ['status','=',1],

            ['end_time','>=',date("Y-m-d",$this->request->time())]

        ])->field('coupon_id,name,valid_bg_time,valid_end_time,coupon_money,money_limit,add_time')

            ->select()->toArray();

        if(empty($coupon_data)) return $this->error('请选择优惠券');







        foreach ($coupon_data as $k => $coupon){

            $member_coupon_model = new MemberCouponModel();

            $member_coupon_data=[

                'shop_id'=>$this->request->shopId,

                'member_id'=>$member_id,

                'type_id'=>2,

                'coupon_id'=>$coupon['coupon_id'],

                'name'=>$coupon['name'],

                'coupon_money'=>$coupon['coupon_money'],

                'money_limit'=>$coupon['money_limit'],

                'valid_bg_time'=>$coupon['valid_bg_time'],

                'valid_end_time'=>$coupon['valid_end_time'],

            ];

            $member_coupon_model->save($member_coupon_data);



            LogsLogic::coupon($this->request->shopId,$member_id,1,2,$member_coupon_model->member_coupon_id,'',$this->request->staffId);

        }



        return $this->success('送券成功');

    }



    public function getMemberCouponList()

    {

        $member_id=$this->request->param('member_id/d',0);

        if(null === $member = MemberModel::find($member_id)) return $this->error('会员不存在');

        if($member->is_delete != 0) return $this->error('会员不存在');

        if($member->shop_id != $this->request->shopId) return $this->error('会员不存在');

        $member->append(['hidden_mobile']);



        $where=[

            ['shop_id','=',$this->request->shopId]

        ];

        if(!empty($member_id)) $where[]=['member_id','=',$member_id];



        $coupons = MemberCouponModel::where($where)

            ->order(['add_time'=>'desc'])

            ->field('member_coupon_id,name,valid_bg_time,valid_end_time,coupon_money,money_limit,status')

            ->limit($this->request->limit)->page($this->request->page)

            ->select()

            ->append(['is_expire'])

            ->toArray();



        $return['coupons']=$coupons;

        if($this->request->page==1){

            $member_info=[

                'member_id'=>$member->member_id,

                'nick_name'=>$member->nick_name,

                'is_vip'=>$member->level ? 1 : 0,

                'level_name'=>$member->level ? $member->level->name : '普通会员',

                'hidden_mobile'=>$member->hidden_mobile,

                'face'=>$member->face,

                'level_discount'=>$member->level ? $member->level->discount : 10,

            ];

            $return['member_info']=$member_info;

        }



        return $this->success($return);

    }



    public function writeOffCoupon()

    {

        //判断权限

        if ($this->request->staff->write_off_jurisdiction !=1) {

            return $this->error('您没有核销的权限');

        }



        $member_id=$this->request->param('member_id/d',0);

        if(null === $member = MemberModel::find($member_id)) return $this->error('会员不存在');

        if($member->is_delete != 0)  return $this->error('会员不存在');

        if($member->shop_id != $this->request->shopId)   return $this->error('会员不存在');



        $member_coupon_id =$this->request->param('member_coupon_id/d',0);

        if(null === $memberCoupon = MemberCouponModel::find($member_coupon_id)) return $this->error('优惠券不存在');

        if($memberCoupon->shop_id != $this->request->shopId) return $this->error('优惠券不存在');

        if($memberCoupon->member_id != $member_id) return $this->error('优惠券不存在');

        if($memberCoupon->status != 0) return $this->error('该优惠券已使用过了');

        if($memberCoupon->valid_end_time <date("Y-m-d")) return $this->error('该优惠券已过期');



        $memberCoupon->status=1;

        $memberCoupon->save();



        LogsLogic::coupon($this->request->shopId,$member_id,-1,6,$member_coupon_id,'',$this->request->staffId);

        return $this->success('核销成功');

    }



    public function getMemberLogsList()

    {

        $member_id=$this->request->param('member_id/d',0);

        if(null === $member = MemberModel::find($member_id)) return $this->error('会员不存在');

        if($member->is_delete != 0)  return $this->error('会员不存在');

        if($member->shop_id != $this->request->shopId)   return $this->error('会员不存在');



        $type=$this->request->param('type/d',1);

        if(!in_array($type,[1,2,3,4])) $type=1;

        $where=[

            ['shop_id','=',$this->request->shopId],

            ['member_id','=',$member_id]

        ];

        switch ($type){

            case 1:

               $datas=MemberBalanceLogsModel::where($where)

                   ->order(['add_time'=>'desc'])

                   ->field('type,info,original_deduction,balance,give_balance,remarks,operate_mobile,operate_name,add_time')

                   ->limit($this->request->limit)

                   ->page($this->request->page)

                   ->select()

                   ->append(['add_time_format','operate_hidden_mobile'])

                   ->toArray();

            break;

            case 2:

                $datas=MemberIntegralLogsModel::where($where)

                    ->order(['add_time'=>'desc'])

                    ->field('type,info,integral,remarks,operate_mobile,operate_name,add_time')

                    ->limit($this->request->limit)

                    ->page($this->request->page)

                    ->select()

                    ->append(['add_time_format','operate_hidden_mobile'])

                    ->toArray();

                break;

            case 3:

                $datas=MemberCouponLogsModel::with(['membercoupon'=>function($query){

                    $query->field('member_coupon_id,coupon_money,name');

                }])->where($where)

                    ->order(['add_time'=>'desc'])

                    ->field('type,info,member_coupon_id,operate_mobile,operate_name,add_time')

                    ->limit($this->request->limit)

                    ->page($this->request->page)

                    ->select()

                    ->append(['add_time_format','operate_hidden_mobile'])

                    ->toArray();

                break;

            default :

                $where[]=['is_paid','=',1];

                $datas=BuyOrderModel::where($where)

                    ->order(['add_time'=>'desc'])

                    ->field('balance,vip_balance,coupon_money,integral_balance,pay_type,use_integral,add_time')

                    ->limit($this->request->limit)

                    ->page($this->request->page)

                    ->select()

                    ->append(['add_time_format','price','pay_type_mean'])

                    ->toArray();

                break;

        }



        return $this->success(['datas'=>$datas]);

    }

}

